<template>
  <view class="history-container">
    <!-- 加载动画 -->
    <view v-if="isLoading" class="loading-placeholder">
      <text>加载中...</text>
    </view>

    <!-- 历史记录按日期分组展示 -->
    <view v-else>
      <view v-for="(group, groupindex) in historyModules" :key="groupindex" class="date-group">
        <!-- 日期分隔线 -->
        <view class="date-divider">
          <text class="date-text">{{ group.date }}</text>
        </view>
		<view
		  v-for="(item, index) in group.items"
		  :key="index"
		  class="clickable-module"
		  @click="handleClick(item)"
		>
		  <pinCell
		    :pinID="item.pinID"
		    publishTime=" "
		  />
		</view>
      </view>
    </view>

    <!-- 没有历史记录时显示的占位内容 -->
    <view v-if="!isLoading && historyModules.length === 0" class="empty-placeholder">
      <text>暂无活动历史记录</text>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore" class="load-more" @click="loadMore">
      <text>加载更多</text>
    </view>
  </view>
</template>

<script>
import pinCell from '../../components/pinCell.vue';  // 引入子组件
import { PinlistAPI } from '../../services/api'; // 引入 API 请求模块
import { SessionAPI,getUserInfo } from '../../services/api'; // 引入 Session API
import { fetchPinInfo } from '../../services/pin'; // 引入 fetchPinInfo

export default {
  components: {
    pinCell,
  },
  data() {
    return {
      historyModules: [], // 分组后的历史记录数据
      isLoading: false, // 是否正在加载
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页记录数
      hasMore: true, // 是否还有更多数据
	  userInfo: null,
    };
  },
  methods: {
    // 获取拼车历史记录并分组
    async loadHistoryData(reload = false) {
      if (this.isLoading) return; // 防止重复加载
      this.isLoading = true;
    
      try {
        if (reload) {
          this.historyModules = [];
          this.currentPage = 1;
        }
    
        const response = await PinlistAPI.getPinlists({
          page: this.currentPage,
          size: this.pageSize,
        });
    
        if (response && response.length) {
          const filteredData = response.filter(item => {
            const departureTime = new Date(item.departureTime);
            return true || departureTime <= new Date(); // 只显示已发生的记录
          });
    
          // 按 departureTime 排序
          filteredData.sort((a, b) => new Date(b.departureTime) - new Date(a.departureTime));
    
          // 按日期分组
          const groupedData = [];
          let currentGroup = [];
          let currentDate = "";
    
          filteredData.forEach(item => {
            const departureDate = this.formatDate(item.departureTime);
			console.log(item);
            // 新增的条件：检查是否是用户相关的记录
			  let members = [];
			  try {
				members = JSON.parse(item.members);  // 将 members 解析为数组
			  } catch (e) {
				console.error('Failed to parse members:', e);
			  }
            const isUserRelated = item.leader == this.userInfo.userID || members.includes(this.userInfo.userID);
    
            // 只有当记录是用户相关时，才会添加到分组中
            if (isUserRelated) {
              if (departureDate !== currentDate) {
                if (currentGroup.length > 0) {
                  groupedData.push({ date: currentDate, items: currentGroup });
                }
                currentGroup = [];
                currentDate = departureDate;
              }
              currentGroup.push(item);
            }
          });
    
          if (currentGroup.length > 0) {
            groupedData.push({ date: currentDate, items: currentGroup });
          }
    
          this.historyModules.push(...groupedData); // 更新分组数据
          this.hasMore = response.length === this.pageSize; // 假设每页返回的数据量等于pageSize则还有更多数据
          this.currentPage += 1; // 更新页码
        }
      } catch (error) {
        console.error("加载历史记录失败：", error);
        uni.showToast({
          title: "加载失败，请稍后再试",
          icon: "none",
        });
      } finally {
        this.isLoading = false;
      }
    },

    // 点击历史记录
    handleClick(record) {
      if (!record || !record.pinID) {
        uni.showToast({
          title: "无效的活动记录",
          icon: "none",
        });
        return;
      }
      uni.navigateTo({
        url: `/pages/pinBranch/pinInvolve?pinID=${record.pinID}`,
      });
    },
    // 加载更多数据
    async loadMore() {
      if (!this.hasMore) return;
      await this.loadHistoryData();
    },
    // 格式化日期
    formatDate(timeString) {
      const date = new Date(timeString);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}/${month}/${day}`;
    },
  },
  // 页面加载时初始化
  async onLoad() {
	this.userInfo=await getUserInfo();
    await this.loadHistoryData(); // 页面加载时获取拼车数据
    uni.$on('updateModule', this.loadPinData); // 监听来自子页面的返回数据
    // this.loadUserInfo(); // 获取用户信息
  },
  onUnload() {
    // 页面销毁时清除事件监听
    uni.$off('updateModule', this.loadPinData);
  }
};
</script>

<style>
.history-container {
  display: flex;
  flex-direction: column;
  padding-top: 5px;
  padding-bottom: 80px;
  gap: 10px;
  padding-left: 20px;
  padding-right: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.date-group {
  margin-bottom: 20px;
}

.date-divider {
  width: 100%;
  text-align: center;
  margin: 10px 0;
}

.date-text {
  display: inline-block;
  padding: 5px 15px;
  background-color: #f0f0f0;
  font-size: 14px;
  color: #888;
  border-radius: 12px;
  font-weight: bold;
}

.loading-placeholder,
.empty-placeholder {
  text-align: center;
  margin-top: 50px;
  color: #666;
  font-size: 16px;
}

.load-more {
  text-align: center;
  padding: 10px 0;
  color: #007aff;
  font-size: 14px;
  cursor: pointer;
}
.clickable-module {
  background-color: transparent; /* 背景透明 */
  color: #333; /* 字体颜色 */
  padding: 0px 11px;
  border: none;
  font-size: 16px;
  cursor: pointer;
  user-select: none;
  width: 100%;  /* 宽度占满父容器 */
  max-width: 400px;  /* 限制最大宽度*/
  margin-left: auto;  /* 左右居中 */
  margin-right: auto;
  text-align: center;
  z-index: 1;
  box-sizing: border-box;
  border-radius: 25px;
}
</style>